import datetime
import json
import os
import random
from urllib import parse, request

import requests

import helper as hp
import jx3_helper as jhp
import win_login

file_qiyu = hp.get_work_dir() + '\\qiyu_latest.dat'
file_cookie = hp.get_work_dir() + '\\cookie.dat'
file_img = hp.get_work_dir() + '\\code.jpg'
refer_url = 'http://www.jx3qy.cn/'
ajax_url = 'http://www.jx3qy.cn/user/login/index.html'
user_agents = [
    'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',
    'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299',
]

headers = {
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Connection': 'keep-alive',
    'Content-Length': '46',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'Host': 'www.jx3qy.cn',
    'Origin': 'http://www.jx3qy.cn/',
    'Referer': refer_url,
    'User-Agent': user_agents[random.randrange(0, 3)],
    'X-Anit-Forge-Code': '0',
    'X-Anit-Forge-Token': 'None',
    'X-Requested-With': 'XMLHttpRequest',
}
my_session = requests.session()
my_cookies = ''
keyword = ''


def get_verify_img():
	img_local = file_img
	verify_code_url = "http://www.jx3qy.cn/user/login/verify.html?id=" + str(random.uniform(0, 1))
	response2 = my_session.get(url=verify_code_url)
	# 在当前文件夹保存为code.jpg，注意要用'b'的二进制写的方式，用content来获得bytes格式
	with open(img_local, 'wb') as fp:
		fp.write(response2.content)
	return img_local


def get_cookie():
	keyword = win_login.show()
	print('key:' + keyword)
	data = {
		'username': 'awer@awer.cn',
		'password': 'aaaaaa',
		'vercode': keyword,
	}
	resp = my_session.post(ajax_url, data=data, headers=headers)
	c = requests.cookies.RequestsCookieJar()  # 利用RequestsCookieJar获取
	c.set('cookie-name', 'cookie-value')
	my_session.cookies.update(c)
	my_cookies = my_session.cookies.get_dict()
	print(my_cookies)
	result = resp.json()
	print(result)
	print('-' * 10)

	f = open(file_cookie, 'w')
	if result['code'] == 1:
		f.write(str(my_cookies))
	else:
		f.write('')
	f.close()

	return result['msg']


def http_get_qy(item):
	my_ck = my_cookies
	if len(my_ck) == 0 and os.path.exists(file_cookie):
		f = open(file_cookie, 'r')
		s = f.read()
		f.close()
		if len(s) > 0:
			my_ck = eval(s)

	if len(my_ck) < 3:
		get_cookie()
		my_ck = my_cookies

	s_url = "http://www.jx3qy.cn/home/qyinfo?m=1&R=电信八区&S=亢龙有悔&t=绝世奇遇&u=%s&n=&csrf=%s" % (item, hp.get_ms_stamp())
	resp = my_session.get(s_url, cookies=my_ck)
	print(resp.text)
	return resp.json()


# 处理http查询结果
def get_str_qy(item, s_val):
	if s_val['code'] == '200':
		if len(s_val['result']) > 0:
			return jhp.str_qq_qy(s_val['result'][0])
		else:
			return '无【%s】的数据' % item
	elif s_val['code'] == '401.4':
		f = open(file_cookie, 'w')
		s = f.write('')
		f.close()
		return s_val['msg']
	else:
		print('cookie：' + s_val['msg'])
		return ''


# 查询单个奇遇
def search_qiyu(item):
	try:
		rejo = http_get_qy(item)
		re_msg = get_str_qy(item, rejo)
	except BaseException as e:
		re_msg = '%s邻居家的Wifi信号丢了，俺%s等会再试。' \
				 '\r\n ' % (hp.str_emoji(128104), hp.ROBOT_NAME)
	return re_msg


# 查询最新奇遇
def search_new_qiyu():
	restr = '1'
	try:
		rejo = http_get_qy('不限')
		if (rejo['code'] == '200'):
			if len(rejo['result']) > 0:
				qy_last = (rejo['result'][0])

				if os.path.exists(file_qiyu):
					f = open(file_qiyu, 'r+')
				else:
					f = open(file_qiyu, 'w+')
				restr = f.read()
				print('read-file:' + restr)
				print('qy_last:' + str(qy_last))

				if str(qy_last) != restr:
					restr = str(qy_last)
					f.seek(0)
					f.truncate()
					f.write(restr)
					restr = (jhp.str_qq_nqy(qy_last))
				else:
					restr = '0'
				f.close()

				if hp.get_second_stamp() - qy_last.get('time') > 2000:  # time expries :10min
					restr = '3'
	except:
		restr = '4'
	return restr


def get_last_qiyu():
	if os.path.exists(file_qiyu):
		f = open(file_qiyu, 'r')
		restr = f.read()
		rejs = eval(restr)
		rejs = (jhp.str_qq_nqy(rejs))
	return rejs


def http_get_daily():
	data = 'category_id=0&add_ad=1&p=1&num=20'
	header = {'Content-Type': 'application/x-www-form-urlencoded',
			  'Content-Length': '33',
			  'Connection': 'Keep-Alive',
			  'Accept-Encoding': 'gzip',
			  'User-Agent': 'okhttp/3.9.0'}
	response = requests.post('http://www.jx3tong.com/?m=api&c=info&a=content_list', data=data, headers=header)
	recv = (response.content.decode('unicode_escape'))
	print(recv)
	return json.loads(recv)['daily_info']


def get_daily():
	daily_info = ''
	now = datetime.datetime.now()
	now_date = now.strftime('%Y-%m-%d')
	seach_date = (now - datetime.timedelta(hours=-8)).strftime('%Y-%m-%d')
	file_daily = hp.get_work_dir() + '\\daily\\'
	hp.chk_dir(file_daily)
	file_daily = file_daily + seach_date + '.dat'
	if os.path.exists(file_daily):
		f = open(file_daily, 'r')
		daily_info = f.read()
		f.close()

	if (len(daily_info) < 10):
		jo = http_get_daily()
		daily_info = jhp.get_dalay_msg(jo)
		if not jhp.is_today_daily(jo):
			daily_info = '日常未更新'

	if len(daily_info) > 10:
		f = open(file_daily, 'w')
		f.write(daily_info.replace('\r', ''))
		f.close()

	return daily_info


def http_price_coin():
	url = ('http://trading.5173.com/list/ViewLastestDealList.aspx?' +
		   'gm=a36ead01453c40b584f8e1e687723f2d&bt=682b60e289f045339cae13d208023fc6' +
		   '&ga=fd41308f5d3c421b80091e0b509b45c4&gs=d17d422ff31845009cda9d1eac8f74c7&' +
		   'ts=-1&raceid=-1&k=&sort=-1&section=-1_-1&pg=1')
	print(url)
	response = requests.get(url)
	# response = requests.get('http://s.5173.com/jx3-5ootfk-2l3v3x-amcatg-0-kb0ewi-0-0-0-a-a-a-a-a-0-itemprice_asc-0-0.shtml')
	recv = (response.content.decode('gb2312'))
	# print(recv)
	return recv


def http_price_coin2():
	# http://yxbmall.5173.com/gamegold-facade-frontend/services/goods/QueryAllCategoryGoods?t=1557751534865&callback=jQuery15206488161429390882_1557751534706&currentUrl=http%3A%2F%2Fs.5173.com%2Fjx3-5ootfk-2l3v3x-amcatg-0-kb0ewi-0-0-0-a-a-a-a-a-0-itemprice_asc-0-0.shtml&_=1557751534866

	url = 'http://yxbmall.5173.com/gamegold-facade-frontend/services/goods/QueryAllCategoryGoods?t=1557751534865&callback=jQuery15206488161429390882_1557751534706&currentUrl=http%3A%2F%2Fs.5173.com%2Fjx3-5ootfk-2l3v3x-amcatg-0-kb0ewi-0-0-0-a-a-a-a-a-0-itemprice_asc-0-0.shtml&_=' + str(
		hp.get_ms_stamp())
	dict1 = {'wd': '百度翻译'}
	url_data = parse.urlencode(dict1)  # unlencode()将字典{k1:v1,k2:v2}转化为k1=v1&k2=v2
	print(url)  # url_data：wd=%E7%99%BE%E5%BA%A6%E7%BF%BB%E8%AF%91
	data = request.urlopen((url)).read()  # 读取url响应结果
	data = data.decode('utf-8')  # 将响应结果用utf8编码
	data = data[data.find('('):]
	data = data.replace('(', "").replace(')', '')
	print(data)
	return json.loads(data)


def get_price_coin():
	html = http_price_coin()
	return jhp.get_price_msg(html)


def get_price_coin2():
	html = http_price_coin2()
	return jhp.get_price_msg2(html)


def get_server_status():
	jo = http_get_server()
	return jhp.get_server_msg(jo)


def get_server_status_timer():
	time_now = datetime.datetime.now()
	week_day = time_now.weekday()
	if week_day == 0 or week_day == 3:
		print('in time area')
		if (time_now.hour > 5 and jhp.server_status != '0') or (time_now.hour < 15 and jhp.server_status == '0'):
			jo = http_get_server()
			re_msg = jhp.get_server_msg_timer(jo)
			print(re_msg)
			return re_msg
		else:
			print('not area')
	return None


def http_get_server():
	response = requests.get('http://www.jx3tong.com/?m=api&c=user&a=server_list&parent=8')
	recv = (response.content.decode('unicode_escape'))
	print(recv)
	return json.loads(recv)['data']

# search_qiyu('少年行')
